<template>
  <div class="upload-container">
    <el-upload
      :action="action"
      :headers="headers"
      :multiple="false"
      :limit="1"
      :before-upload="beforeUpload"
      :on-success="onSuccess"
      :on-error="onError"
      :on-remove="onRemove"
      :on-change="handleChange"
      :file-list="fileList"
      :on-exceed="onExceed"
      :disabled="disable"
      :drag="drag"
      :list-type="listType"
      show-file-list
      accept=".jpg, .jpeg, .png, .gif, .bmp, .JPG, .JPEG, .PBG, .GIF, .BMP"
      class="single-image-upload"
    >
      <div v-if="drag">
        <i class="el-icon-upload" />
        <div v-if="fileList.length === 0" class="el-upload__text">
          请将图片拖入或<em>点击上传</em>
        </div>
        <div v-else class="el-upload__text">
          图书已经上传
        </div>
      </div>
      <div v-else>
        <el-button size="small" type="primary">点击上传</el-button>
      </div>
    </el-upload>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
export default {
  props: {
    fileList: {
      type: Array,
      default() {
        return []
      }
    },
    disable: {
      type: Boolean,
      default: false
    },
    drag: {
      type: Boolean,
      default: false
    },
    listType: {
      type: String,
      default: 'text'
    }
  },
  data() {
    return {
      action: '/api/admin/Upload/singleImage'
    }
  },
  computed: {
    ...mapGetters([
      'token'
    ]),
    headers() {
      return {
        'x-token': this.token
      }
    }
  },
  methods: {
    beforeUpload(file) {
      this.$emit('beforeUpload', file)
    },
    onSuccess(response, file) {
      const { message, data, status } = response
      if (status === 1) {
        this.$message({
          message: message,
          type: 'success'
        })
        this.$emit('onSuccess', data, file)
      } else {
        this.$message({
          message: message || '上传失败',
          type: 'error'
        })
        this.$emit('onError', file)
      }
    },
    onError(err) {
      const errMsg = err.message && JSON.parse(err.message)
      this.$message({
        message: (errMsg && errMsg.message && '上传失败,失败原因：' + errMsg.message) || '上传失败',
        type: 'error'
      })
      this.$emit('onError', err)
    },
    onRemove(file) {
      // this.$message({
      //   message: '电子书删除成功',
      //   type: 'success'
      // })
      this.$emit('onRemove')
    },
    handleChange(file, fileList) {
      this.$emit('handleChange', file, fileList)
    },
    onExceed() {
      this.$message({
        message: '每次只能上传一张图片',
        type: 'warning'
      })
    }

  }
}
</script>

<style scoped>

</style>
